#include "test-item-wifi-connect.h"

#define  ERRLOG(errmsg)  do{\
                                perror(errmsg);\
                                printf("%s-%s-%d\n", __FILE__, __func__, __LINE__);\
                            }while(0)

bool test_item_wifi_connect_work_flag;
bool test_item_wifi_connect_thread_no_created = true;

TestItemWiFiConnect::TestItemWiFiConnect()
{
}

TestItemWiFiConnect::~TestItemWiFiConnect()
{
}

int test_item_get_localip(const char * eth_name, char *local_ip_addr)
{
	int ret = -1;
    register int fd;
    struct ifreq ifr;
 
	if (local_ip_addr == NULL || eth_name == NULL)
	{
		return ret;
	}
	if ((fd=socket(AF_INET, SOCK_DGRAM, 0)) > 0)
	{
		strcpy(ifr.ifr_name, eth_name);
		if (!(ioctl(fd, SIOCGIFADDR, &ifr)))
		{
			ret = 0;
			strcpy(local_ip_addr, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
		}
	}
	if (fd > 0)
	{
		close(fd);
	}
    return ret;
}

void *wifi_connect_work_pthread(void *arg)
{
    TestModuleFrameFormat *argFrameFormat = (TestModuleFrameFormat *)arg;
    int ret;
    uint8_t send_data[256];
    uint8_t send_length;
    send_data[0] = TEST_WIFI_CONNECT;

	char local_ip[20] = {0};

    int sockfd, acceptfd;
    struct sockaddr_in serveraddr, clientaddr;
    socklen_t addrlen = sizeof(serveraddr);
 
    //获取本地IP地址
	ret = test_item_get_localip("wlan0", local_ip);
	if (ret == 0)
	{
		printf("local ip 1:%s\n", local_ip);
	}
    // //发送本机IP给上位机
    // sleep(1);
    // send_data[1] = TEST_TRANSFER_WLAN_IP;
    // memcpy(&send_data[2], local_ip, strlen(local_ip));
    // send_length += 2 + strlen(local_ip);
    // argFrameFormat->framePackageFunction(send_data, send_length);

    //第一步：创建套接字
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        ERRLOG("socket error");
    }

    //设置端口复用
    int on  = 1;
    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
    {
        ERRLOG("setsockopt error");
    }

    //第二步：填充服务器网络信息结构体
    //inet_addr:将点分十进制ip地址转化为无符号32位整形数据
    //htons:将主机字节序转化为网络字节序
    //atoi:将数字型字符串转化为整形数据
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(local_ip);
    serveraddr.sin_port = htons(atoi("8888"));

    //第三步：将套接字与服务器网络信息结构体绑定
    if(bind(sockfd, (struct sockaddr *)&serveraddr, addrlen) == -1)
    {
        ERRLOG("bind error");
        return nullptr;
    }

    //第四步：将套接字设置为被动监听状态
    if(listen(sockfd, 5) == -1)
    {
        ERRLOG("listen error");
        return nullptr;
    }

    //第五步：阻塞等待客户端的连接
    if((acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen)) == -1)
    {
        ERRLOG("accept error");
        return nullptr;
    }

    //获取客户端信息
    printf("[%s:%d]连接了\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));

    //进行通信
    char buf[256] = {0};
    ssize_t bytes;
    while(test_item_wifi_connect_work_flag)
    {
        //接收数据
        //如果发送方结束，recv就会返回0，所以需要将返回0的清空考虑一下
        if((bytes = recv(acceptfd, buf, sizeof(buf), 0)) == -1)
        {
            ERRLOG("recv error");
            break;
        }
        else if(bytes == 0)
        {
            printf("客户端[%s:%d]退出了\n",  inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
            close(acceptfd);
            close(sockfd);
            break;
        }

        if(strcmp(buf, "quit") == 0)
        {
            printf("客户端[%s:%d]退出了\n",  inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
            close(acceptfd);
            close(sockfd);
            break;
        }

        printf("client: %s\n", buf);

        //发送数据给客户端
        //如果读端关闭，当send第二次运行的时候就会产生一个SIGPIPE信号，这个
        //信号对当前进程的默认处理方式是结束进程
        if(send(acceptfd, buf, sizeof(buf), 0) == -1)
        {
            ERRLOG("send error");
            break;
        }
    }
    // close(config_fd);
    test_item_wifi_connect_thread_no_created = true;
    printf("WiFi连接测试线程退出！\n");
    return nullptr;
}

int TestItemWiFiConnect::recv_command_data(void *data, uint16_t length)
{
    if((NULL == data) || (length < 2))
    {
        printf("传入参数错误！\n");
        return -1;
    }

    int ret;
    uint8_t recvBuffer[length] = {0};
    uint8_t sendBuffer[2] = {0};
    sendBuffer[0] = TEST_WIFI_CONNECT;

    memcpy(recvBuffer, data, length);

    if(recvBuffer[1] == TEST_START)//开始
    {
        test_item_wifi_connect_work_flag = true;
        if(test_item_wifi_connect_thread_no_created)
        {
            ret = pthread_create(&work_pthread, NULL, wifi_connect_work_pthread, (void *)&frameOperate);
            if(ret == -1)
            {
                printf("WiFi连接测试，创建线程失败！\n");
                return ret;
            }else
            {
                test_item_wifi_connect_thread_no_created = false;
            }
        }
        sendBuffer[1] = TEST_STARTED;
        frameOperate.framePackageFunction(sendBuffer, sizeof(sendBuffer));
        printf("WiFi连接测试开始！\n");

        uint8_t send_data[256] = {0};
        uint8_t send_length = 0;
        char local_ip[20] = {0};
        //获取本地IP地址
        ret = test_item_get_localip("wlan0", local_ip);
        if (ret == 0)
        {
            printf("local ip 2:%s\n", local_ip);
        }
        //发送本机IP给上位机
        sleep(1);//与上一次发送间隔开
        send_data[0] = TEST_WIFI_CONNECT;
        send_data[1] = TEST_TRANSFER_WLAN_IP;
        memcpy(&send_data[2], local_ip, strlen(local_ip));
        send_length += 2 + strlen(local_ip);
        frameOperate.framePackageFunction(send_data, send_length);
    }else if(recvBuffer[1] == TEST_STOP)//停止
    {
        test_item_wifi_connect_work_flag = false;
        sendBuffer[1] = TEST_STOPED;
        frameOperate.framePackageFunction(sendBuffer, sizeof(sendBuffer));
        printf("WiFi连接测试结束！\n");
    }else
    {
        printf("数据错误：%x , %x \n", recvBuffer[0], recvBuffer[1]);
    }

    return 0;
}
